/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.service.impl;

import com.minierp.bean.OutBillBean;
import com.minierp.bean.OutBillItemBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.BusinessBillDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.OutBillDao;
import com.minierp.dao.OutBillItemDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.dao.StockBalanceDao;
import com.minierp.dao.StockDao;
import com.minierp.err.DataChangedException;
import com.minierp.err.NotAllowException;
import com.minierp.err.StockNoEnoughException;
import com.minierp.helper.PageHelper;
import com.minierp.model.BusinessBill;
import com.minierp.model.BusinessBillExt;
import com.minierp.model.BusinessProfit;
import com.minierp.model.OutBill;
import com.minierp.model.OutBillItem;
import com.minierp.service.OutBillService;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OutBillServiceImpl implements OutBillService {
	public void txInsert(OutBillBean form, OutBillDao outBillDao,
			OutBillItemDao outBillItemDao, StockDao stockDao,
			StockBalanceDao stockBalanceDao, SerialNumberDao serialNumberDao,
			BusinessBillDao businessBillDao, IdGenerator idGenerator)
			throws Exception {
		OutBill obj = form.getOutBill();
		obj.setCreateTime(new Date());
		obj.setId(idGenerator.getId(OutBill.class.getName()));
		if (!form.getCodeRule().getGenerateRule().equals("MANUAL")) {
			obj.setBillCode(PageHelper.generateCode(serialNumberDao,
					form.getCodeRule(), "", form.getOutBill().getTallySetId()));

			for (OutBill updateStock = outBillDao.get(obj.getBillCode()); updateStock != null; updateStock = outBillDao
					.get(obj.getBillCode())) {
				obj.setBillCode(PageHelper.generateCode(serialNumberDao, form
						.getCodeRule(), "", form.getOutBill().getTallySetId()));
			}
		}

		boolean updateStock1 = false;
		if (obj.getExamined().equals("Y")) {
			obj.setExamineTime(new Date());
			updateStock1 = true;
		}

		outBillDao.save(obj);
		BigDecimal outCost = this.saveItems(obj, updateStock1,
				form.getRequirerName(), form.getItems(), outBillItemDao,
				stockDao, stockBalanceDao, idGenerator);
		if (obj.getExamined().equals("Y")) {
			this.updateBusinessProfit("SUB", obj.getBusinessBillCode(),
					outCost, businessBillDao, idGenerator);
		}

	}

	private void updateBusinessProfit(String countType, String bbCode,
			BigDecimal outCost, BusinessBillDao businessBillDao,
			IdGenerator idGenerator) {
		if (bbCode != null && !bbCode.equals("")) {
			BusinessBill bb = businessBillDao.get(bbCode);
			if (bb != null) {
				BusinessBillExt be = (BusinessBillExt) businessBillDao.get(
						BusinessBillExt.class, bb.getId());
				BusinessProfit p = businessBillDao.getBusinessProfit(bbCode);
				if (p == null) {
					p = new BusinessProfit();
					p.setBbCode(bbCode);
					p.setId(idGenerator.getId(BusinessProfit.class.getName()));
					p.setCooperCost(new BigDecimal(0));
					p.setFeeCost(new BigDecimal(0));
					if (countType.equals("ADD")) {
						p.setMaterialCost((new BigDecimal(0)).subtract(outCost));
					} else {
						p.setMaterialCost(outCost);
					}

					p.setProfitCost(bb.getCost().add(be.getAdjustCost())
							.subtract(p.getMaterialCost()));
					businessBillDao.save(p);
				} else {
					if (countType.equals("ADD")) {
						p.setMaterialCost(p.getMaterialCost().subtract(outCost));
						p.setProfitCost(p.getProfitCost().add(outCost));
					} else {
						p.setMaterialCost(p.getMaterialCost().add(outCost));
						p.setProfitCost(p.getProfitCost().subtract(outCost));
					}

					businessBillDao.update(p);
				}
			}
		}

	}

	public void txUpdate(OutBillBean form, OutBillDao outBillDao,
			OutBillItemDao outBillItemDao, StockDao stockDao,
			StockBalanceDao stockBalanceDao, BusinessBillDao businessBillDao,
			IdGenerator idGenerator) throws Exception {
		OutBill obj = form.getOutBill();
		Object[] sv = outBillDao.getStatusValues(obj.getId());
		if (sv == null) {
			throw new Exception("Can\'t get status values for in bill:"
					+ obj.getId());
		} else {
			long existSycVal = ((Date) sv[0]).getTime();
			String exitEnabled = sv[1].toString();
			String existExamined = sv[2].toString();
			if (existSycVal != form.getSychronizeValue()) {
				throw new DataChangedException("出库单已被其他操作修改，请关闭页面再打开后重新操作！");
			} else if (exitEnabled.equals("N")) {
				throw new NotAllowException("出库单已作废，不能修改！");
			} else if (existExamined.equals("Y")) {
				throw new NotAllowException("出库单已审核，不能修改！");
			} else {
				boolean updateStock = false;
				if (obj.getExamined().equals("Y")) {
					obj.setExamineTime(new Date());
					updateStock = true;
				}

				obj.setUpdateTime(new Date());
				outBillDao.update(obj);
				BigDecimal outCost = this.saveItems(obj, updateStock,
						form.getRequirerName(), form.getItems(),
						outBillItemDao, stockDao, stockBalanceDao, idGenerator);
				if (obj.getExamined().equals("Y")) {
					this.updateBusinessProfit("SUB", obj.getBusinessBillCode(),
							outCost, businessBillDao, idGenerator);
				}

			}
		}
	}

	private BigDecimal saveItems(OutBill outBill, boolean updateStock,
			String requName, List<?> items, OutBillItemDao outBillItemDao,
			StockDao stockDao, StockBalanceDao stockBalanceDao,
			IdGenerator idGenerator) throws StockNoEnoughException,
			ParseException {
		int newNum = 0;

		for (int curItemId = 0; curItemId < items.size(); ++curItemId) {
			OutBillItemBean bean = (OutBillItemBean) items.get(curItemId);
			if (bean.getStatus().equals("NEW")) {
				++newNum;
			}
		}

		long arg14 = 0L;
		if (newNum > 0) {
			arg14 = idGenerator.getId(OutBillItem.class.getName(), newNum);
		}

		ArrayList itemList = new ArrayList();

		for (int outCost = 0; outCost < items.size(); ++outCost) {
			OutBillItemBean bean1 = (OutBillItemBean) items.get(outCost);
			bean1.getOutBillItem().setBillId(outBill.getId());
			if (bean1.getStatus().equals("DELETE")) {
				if (bean1.getOldId() != 0L) {
					outBillItemDao.delete(bean1.getOldId());
				}
			} else if (bean1.getStatus().equals("EDIT")) {
				outBillItemDao.update(bean1.getOutBillItem());
				itemList.add(bean1.getOutBillItem());
			} else if (bean1.getStatus().equals("NEW")) {
				bean1.getOutBillItem().setId(arg14);
				outBillItemDao.save(bean1.getOutBillItem());
				++arg14;
				itemList.add(bean1.getOutBillItem());
			} else {
				itemList.add(bean1.getOutBillItem());
			}
		}

		BigDecimal arg15 = new BigDecimal(0);
		if (updateStock) {
			arg15 = PageHelper
					.updateOutBillStock(outBill, itemList, stockDao,
							stockBalanceDao, idGenerator, requName,
							"SAVE_EXAM", "", "");
		}

		return arg15;
	}

	public void txExamine(long id, OutBillDao outBillDao,
			OutBillItemDao outBillItemDao, StockDao stockDao,
			StockBalanceDao stockBalanceDao, BusinessBillDao businessBillDao,
			IdGenerator idGenerator, UserBean ub)
			throws StockNoEnoughException, ParseException {
		OutBill b = (OutBill) outBillDao.get(OutBill.class, id);
		if (b != null && b.getEnabled().equals("Y")
				&& b.getExamined().equals("N")) {
			b.setExamined("Y");
			b.setExamineTime(new Date());
			b.setUpdateTime(new Date());
			b.setExaminerId(ub.getStaffer().getId());
			b.setExaminerName(ub.getStaffer().getStafferName());
			outBillDao.update(b);
			String requName = PageHelper.getRequName(b.getRequirerId(),
					b.getRequirerType(), outBillDao);
			List itemList = outBillItemDao.getList(b.getId());
			BigDecimal outCost = PageHelper.updateOutBillStock(b, itemList,
					stockDao, stockBalanceDao, idGenerator, requName, "EXAM",
					"", "");
			this.updateBusinessProfit("SUB", b.getBusinessBillCode(), outCost,
					businessBillDao, idGenerator);
		}

	}

	public void txUnExamine(long id, OutBillDao outBillDao,
			OutBillItemDao outBillItemDao, StockDao stockDao,
			StockBalanceDao stockBalanceDao, BusinessBillDao businessBillDao,
			IdGenerator idGenerator, UserBean ub)
			throws StockNoEnoughException, ParseException {
		OutBill b = (OutBill) outBillDao.get(OutBill.class, id);
		if (b != null && b.getEnabled().equals("Y")
				&& b.getExamined().equals("Y")) {
			b.setExamined("N");
			b.setUpdateTime(new Date());
			b.setExaminerId(0L);
			b.setExaminerName("");
			outBillDao.update(b);
			String requName = PageHelper.getRequName(b.getRequirerId(),
					b.getRequirerType(), outBillDao);
			List itemList = outBillItemDao.getList(b.getId());
			BigDecimal outCost = PageHelper.updateOutBillStock(b, itemList,
					stockDao, stockBalanceDao, idGenerator, requName,
					"UN_EXAM", ub.getStaffer().getStafferName(), "");
			this.updateBusinessProfit("ADD", b.getBusinessBillCode(), outCost,
					businessBillDao, idGenerator);
		}

	}

	public void txCancel(long id, String reason, OutBillItemDao outBillItemDao,
			StockDao stockDao, StockBalanceDao stockBalanceDao,
			BusinessBillDao businessBillDao, IdGenerator idGenerator,
			UserBean ub) throws Exception {
		OutBill b = (OutBill) outBillItemDao.get(OutBill.class, id);
		BusinessBill bb = null;
		BigDecimal bbAdju = null;
		if (b != null && b.getEnabled().equals("Y")
				&& b.getBusinessBillCode() != null
				&& !b.getBusinessBillCode().equals("")) {
			bb = businessBillDao.get(b.getBusinessBillCode());
			if (bb != null) {
				BusinessBillExt be = (BusinessBillExt) businessBillDao.get(
						BusinessBillExt.class, bb.getId());
				bbAdju = be.getAdjustCost();
			}
		}

		PageHelper.cancelOutBill(b, ub, reason, bb, bbAdju, "NORM",
				outBillItemDao, businessBillDao, stockDao, stockBalanceDao,
				idGenerator);
	}
}